

/**
 * 
 *   @author   周建建
 *   start_time    2019-11-7
 * 
 */

!function($wx,...$list){
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [路由地址，参数，请求方式,如需回调请传函数]
   */
  $wx.$ajax = (...arrays) => {
    let openid = null, nums = 0;
    $list[0].edit ? '' : arrays = [];
    return new Promise(
      (resolve, reject) => {
        let call_fn = (id, callback) => {
          let token = wx.getStorageSync('token');
          nums += 1;
          wx.request({
            url: wx.$config.serverAddress + arrays[0],
            data: JSON.stringify({ token, data: arrays[1] }),
            dataType: 'json',
            method: arrays[2].toUpperCase() || 'POST',
            header: typeof arrays[3] == "object" ? arrays[3] : {
              'content-type': 'application/x-www-form-urlencoded',
              // 'OPENID': id || getApp().config.openid ||wx.getStorageSync("openid")||'',
              // 'OPENID':'osSQa4_n9Uv1L03kd0r820iEQICY'
            },
            success: res => {
              resolve(res)
              typeof arrays[3] == "function" ? arrays(res) : null
            },
            fail: err => {
              reject(err)
            },
            complete: all => {
              wx.hideLoading();
              wx.hideToast()
              wx.hideNavigationBarLoading();
              console.log(all, 'sssssssssss')
              if(all.data.code == 400){
                wx.login({
                  success: res => {
                    if (res.code) {
                        wx.request({
                          url: wx.$config.serverAddress + 'api/weixinLogin',
                          data: { data: { code: res.code, from: 'employee' } },
                          header: {
                            'content-type': 'application/json'
                          },
                          success(response) {
                            if (response.data.code == 200) {
                              wx.setStorageSync('token', response.data.data.token);
                              if(typeof callback == 'function'){
                                callback(id, callback)
                              }
                            }
                          }
                        })
                    }
                  }
                })
              }
              if (all.statusCode != 200) {
                wx.reLaunch({
                  url: '/pages/error/error',
                })
              } else {
                reject(all)
              }
            }
          })
        }
        call_fn(openid, call_fn)
      }
    )
  }

  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [字段名，0升序  1降序  【字段比大小】]
   */
  $wx.$sort=(...arrays)=>{
    return function (a, b) {
      var value1 = a[arrays[0]];
      var value2 = b[arrays[0]];
      if (arrays[1] == 1) {
        return value2 - value1;
      } else {
        return value1 - value2;
      }
    }
  }
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [数组 [{}]，字段名称,0升序  1降序  【字段比大小】]
   */
  $wx.$sortTime=(...arrays)=>{
    arrays[0].sort(function (a, b) {
      if (arrays[2] == 1) {
        return Date.parse(a[arrays[1]]) - Date.parse(b[arrays[1]]); //时间正序
      } else {
        return Date.parse(b[arrays[1]]) - Date.parse(a[arrays[1]])
      }
    });
    return arrays[0]
  }
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [数组 [{}]，字段名称]
   */
  $wx.$Distinct=(...arrays)=>{
    var hash = {};
    return arrays[0].reduce(function (item, next) {
      hash[next[arrays[1]]] ? '' : hash[next[arrays[1]]] = true && item.push(next);
      return item;
    }, []);
  }
  /**
   *   @method
   *   缓存手机设备信息
   *   手机高度、宽度、iphonex~苹果手机 特定高度问题
   */
  $wx.$facility=()=>{
    let set_s      =wx.setStorageSync;
    wx.getSystemInfo({
      success: function (res) {
        let totalTopHeight = 68
        if (res.model.indexOf('iPhone X') !== -1) {
          totalTopHeight = 88
        } else if (res.model.indexOf('iPhone') !== -1) {
          totalTopHeight = 64
        }
        set_s('statusBarHeight', res.statusBarHeight);
        set_s('titleBarHeight', totalTopHeight - res.statusBarHeight);
        set_s("phoneW", res.screenWidth);
        set_s("phoneH", res.screenHeight);
        set_s("windowH", res.windowHeight);
        $wx.phoneH = res.screenHeight || 0;
        $wx.phoneW = res.screenWidth || 0;
      },
      failure() {
        set_s('statusBarHeight', 0)
        set_s('titleBarHeight', 0)
      }
    })
  }


  /**
   *  @method
   *  @param {String}  title
   *  @param  {Number}  time
   *  弹框提示
   * 
   */
  $wx.$title=(title, time)=>{
    wx.showToast({
      title: title,
      icon: 'none',
      duration: time || 1000
    })
  }

  /**
   *  @method
   *  @param  {String}  url
   *  @param  {Array}  urlList
   *  图片阅览
   * 
   */
  $wx.$imgRead=(url, urlList)=>{
    wx.previewImage({
      current: url,                   // 当前显示图片的http链接
      urls: urlList ? urlList : [url] // 需要预览的图片http链接列表
    })
  }

  /**
   *  @method
   *  @param  {String}  title
   *  设置字体
   * 
   */
  $wx.$setTop=(title)=>{
    wx.setNavigationBarTitle({
      title: title
    })
  }

  
  /**
   *  @method
   *  @param  {String}  fc   
   * @param   {String}  bc
   *  设置顶部背景颜色
   * 
   */
  $wx.$setTopBk=(fc, bc)=>{
    wx.setNavigationBarColor({
      frontColor: fc || '#000000',
      backgroundColor: bc || '#ffffff',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  }

  
  /**
   *  @method
   *  @param   {Number}  num
   *  @param   {Number}  time
   *  设置页面滚动的位置
   * 
   */
  $wx.$scrollTop=(num, time)=>{
    wx.pageScrollTo({
      scrollTop: num || 0,
      duration: time || 300
    })
  }

  /**
   *  @method
   *  @param   {Array}  arr
   *  @param   {String}  key
   *  去重  传入(数组, 去重字段名)
   * 
   */
  $wx.$unique=(arr, key)=>{
    const res = new Map();
    return arr.filter((a) => !res.has(a[key]) && res.set(a[key], 1))
  }

  /**
   * 时间戳转时间
   */
  $wx.$timestamp=(stamp, type)=>{
    // 判断是不是13位的时间戳格式
    if (stamp.length < 13) {
      stamp = stamp * 1000
    } else {
      stamp = stamp
    }
    let date = new Date(Number(stamp)),
    year = date.getFullYear(),
    month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1),
    day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate(),
    hour = date.getHours() > 9 ? date.getHours() : '0' + date.getHours(),
    minute = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes(),
    second = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
    if(type === 'year'){
      return year
    }else if(type === 'month'){
      return year + '-' + month
    }else if(type === 'day'){
      return year + '-' + month + '-' + day
    }else{
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
    }
  }

  /**
   * 计算列表容器高度
   */
  $wx.computeHeight=(className, cb)=>{
    wx.getSystemInfo({
      complete: (res) => {
        const query = wx.createSelectorQuery()
        query.select(className).boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function (r) {
          cb(res.windowHeight - r[0].height)
        })
      },
    })
  }

  /**
   * 长按保存图片
   */
  $wx.saveImage = (url)=>{
    wx.getImageInfo({
      src: url,
      success(res){
        let path = res.path
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success(res) {
            console.log(res);
          },
          fail(err) {
            console.log(path, err)
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success:modalSuccess=>{
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData",failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          }
        })
      }
    })
  }
 
}(typeof wx=="object"?wx:new Object(),
    wx.$config,

)